#!/bin/sh

# DESCRIPTION:
#  pkg-config file compilation script.
#
# ARGUMENTS:
#  $1 (string): library version
#  $2 (string): library name

# ARGUMENT CHECK
if [[ -z "$1" ]] || [[ -z "$2" ]]; then
    echo "Missing parameter."
    echo "Usage: $0 LIB_VERSION LIB_NAME"
    exit 1
fi

# ARGUMENTS
LIB_VERSION="$1"
LIB_NAME="$2"
LIB_FILENAME="lib${LIB_NAME}.so"

# CONSTANTS
PKGCONFIG_FILENAME="${LIB_NAME}.pc"
TEMPLATE_FILENAME="${PKGCONFIG_FILENAME}.template"
# TEMPLATE_FILENAME needs to be checked immediately
if [[ ! -f "$TEMPLATE_FILENAME" ]]; then
    echo "Error, the template file does not exist."
    exit 1
fi
#
TEMPLATE_CONTENT=$(cat "$TEMPLATE_FILENAME")

# GLOBAL VARIABLES
LIB_PREFIX="/usr"
LIB_TITLE="IceCode Graphics"
LIB_DESCRIPTION="IceCoder's graphics tools"
LIB_URL="" #TODO: Set URL
LIB_REQUIRES="gl"
LIB_LIBS="-l$LIB_NAME"
LIB_CFLAGS="-std=c++0x -D_ICECODE_GRAPHICS"

# DESCRIPTION:
#  Compiles the template of the pkg-config file.
function compile()
{
    echo "$TEMPLATE_CONTENT" | sed -e "s|@prefix@|$LIB_PREFIX|" \
	-e "s|@name@|$LIB_TITLE|" \
	-e "s|@description@|$LIB_DESCRIPTION|" \
	-e "s|@version@|$LIB_VERSION|" \
	-e "s|@url@|$LIB_URL|" \
	-e "s|@requires@|$LIB_REQUIRES|" \
	-e "s|@libs@|$LIB_LIBS|" \
	-e "s|@cflags@|$LIB_CFLAGS|"
}

# DESCRIPTION:
#  Writes the compiled pkg-config file.
#
# ARGUMENTS:
# $1 (string): The content of the file to be written.
function writePKG()
{
    echo "$1" > $PKGCONFIG_FILENAME
}

# MAIN CODE
OUTPUT_NEW=$(compile)

#if file exists and it's content is NOT up to date, then re-write it.
if [[ -f "$PKGCONFIG_FILENAME" ]]; then
    if [[ "$OUTPUT_NEW" != "$(cat $PKGCONFIG_FILENAME)" ]]; then
	echo "pkg-config file exists but is not up to date, rewriting..."
	writePKG "$OUTPUT_NEW"
    else
	echo "pkg-config file exists and is up to date."
    fi
else
    echo "pkg-config file does not exist, creating..."
    writePKG "$OUTPUT_NEW"
fi
